<script setup lang="ts">
import { ref, computed } from 'vue';
import { useCountDown } from '@vant/use';
import { sendSms } from '@/common/api/register';

const props = defineProps<{ mobile: string }>();
const emit = defineEmits<{
  (e: 'onVerifyMobile'): void;
}>();

const first = ref(true);

// 倒计时60秒
const countDown = useCountDown({
  time: 60 * 1000,
  onFinish() {
    countDown.reset();
  },
});

// 倒计时是否开启 true:倒计时已开启
const isStart = computed(() => countDown.current.value.total / 1000 !== 60);

// 按钮文案
const text = computed(() => {
  let t = '';
  if (!isStart.value) {
    t = first.value ? '发送验证码' : '重新获取';
  } else {
    t = `${(countDown.current.value.total / 1000).toFixed(0)}s`;
  }
  return t;
});

// 开启倒计时
const startCountDown = () => {
  countDown.start();
  first.value = false;
};

// 获取验证码
const loading = ref(false);
const handleClickCode = async () => {
  if (!props.mobile) return emit('onVerifyMobile');
  if (isStart.value) return false;
  loading.value = true;
  try {
    await sendSms({ mobile: props.mobile });
    startCountDown();
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};
</script>
<template>
  <div class="getCode">
    <van-loading v-if="loading" size="24px" />
    <div
      v-else
      class="cursor-pointer"
      :style="{ color: isStart ? 'var(--van-cell-value-color)' : '#f5b94b' }"
      @click="handleClickCode"
    >
      {{ text }}
    </div>
  </div>
</template>
